Skip to main content

matplotlib plotting with time as horizontal coordinate, using dataframe data

· 2 Minutes to read
Allen Ma

Origins

When I was using a SQL database as a data source, I found that I was getting mostly time series data, and I really wanted to draw line graphs with time as the horizontal coordinate. I wanted the freedom to set the time interval, and the canvas size.

import matplotlib.pyplot as plt
import pandas as pd
import pymssql
import warnings
from pylab import *
import matplotlib.dates as mdates

warnings.filterwarnings('ignore')

connect = pymssql.connect('IP地址','用户名','密码','数据库名')
print("连接成功")
data = pd.read_sql("select TRADEDATE,cast(TCLOSE as int) from TQ_QT_SKDAILYPRICE where SECODE='2010000512'", con=connect)
#print(data.head()) #View the results of the reading
data.columns = ['day','close']
#print(data.head()) #View the results of the reading
data['day'] = pd.to_datetime(data['day']) #Convert to date, otherwise the date settings below will not work

#The matplotlib.pyplot approach
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

fig = plt.figure(figsize=(20, 5))
ax = fig.add_subplot(1, 1, 1)

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) #Set the format of the x-axis main scale display (date)
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=15)) #Set the x-axis main scale interval

plt.xlabel('日期')
plt.ylabel('收盘价')
plt.title('2010000512收盘价折线图')
plt.plot(data['day'],data['close'])
plt.show()

Results of the run. 在这里插入图片描述

Adjust the canvas size

fig = plt.figure(figsize=(20, 5))

20 and 5 are the length and width of the canvas respectively.

Control the normal display of Chinese characters and plus and minus signs

plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

Set the x-axis master scale display format (date)

import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

'%Y-%m' can be freely selected from '%y-%m-%d %H:%M'. The year, month, day, hour and minute are displayed respectively.

Set x-axis main scale spacing

import matplotlib.dates as mdates
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=15))

Change the sparsity of the horizontal labels by changing the size of the interval assignment. The larger the interval, the more sparse it is.